/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.ws;

import com.ws.cli.CliOptions;
import com.ws.cli.CliOptionsParser;
import com.ws.cli.SqlCommandParser;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.table.api.EnvironmentSettings;
import org.apache.flink.table.api.SqlParserException;
import org.apache.flink.table.api.TableEnvironment;
import org.apache.flink.table.catalog.Catalog;
import org.apache.flink.table.catalog.CatalogDatabaseImpl;
import org.apache.flink.table.catalog.hive.HiveCatalog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

/**
 * @author wangshuai
 */
public class SqlSubmit {
    private static final Logger logger = LoggerFactory.getLogger(SqlSubmit.class);
    public static final String DELIMITER = "-";

    public static void main(String[] args) throws Exception {
        final CliOptions options = CliOptionsParser.parseClient(args);
        SqlSubmit submit = new SqlSubmit(options);
        submit.run();
    }

    // --------------------------------------------------------------------------------------------

    private final String sqlFilePath;
    private final String workSpace;
    private final String hiveConfig;
    private final String catalog;
    private final String database;
    private TableEnvironment tEnv;

    private SqlSubmit(CliOptions options) {
        this.sqlFilePath = options.getSqlFilePath();
        this.workSpace = options.getWorkingSpace();
        this.hiveConfig = options.getHiveConfig();
        this.catalog = options.getCatalog();
        this.database = options.getDatabase();
    }

    private void run() throws Exception {
        EnvironmentSettings settings = EnvironmentSettings.newInstance()
                .useBlinkPlanner()
                .inStreamingMode()
                .build();
        this.tEnv = TableEnvironment.create(settings);
        if (StringUtils.isNotBlank(hiveConfig)) {
            Catalog hiveCatalog = new HiveCatalog(catalog, null, hiveConfig);
            this.tEnv.registerCatalog(catalog, hiveCatalog);
            this.tEnv.useCatalog(catalog);
            hiveCatalog.createDatabase(database,
                    new CatalogDatabaseImpl(new HashMap<>(0),
                            "database automatically created during execution"),
                    true);
            this.tEnv.useDatabase(database);
        }
        DirectoryStream<Path> pathDirectoryStream = Files.newDirectoryStream(Paths.get(workSpace), sqlFilePath);
        Iterator<Path> iterator = pathDirectoryStream.iterator();
        List<Path> pathsList = new ArrayList<>();
        while (iterator.hasNext()) {
            Path next = iterator.next();
            pathsList.add(next);
        }
        pathsList.sort(new Comparator<Path>() {
            @Override
            public int compare(Path o1, Path o2) {
                String[] first = o1.getFileName().toString().split(DELIMITER);
                String[] tow = o2.getFileName().toString().split(DELIMITER);
                try {
                    return Integer.parseInt(first[0]) - Integer.parseInt(tow[0]);
                } catch (Exception ignored) {
                    logger.warn("The first paragraph of the file name is not a number. The sql file cannot be sorted. If you need to sort, please set");
                }
                return 0;
            }
        });
        for (Path path : pathsList) {
            List<String> sql = Files.readAllLines(path);
            List<SqlCommandParser.SqlCommandCall> calls = SqlCommandParser.parse(sql);
            for (SqlCommandParser.SqlCommandCall call : calls) {
                callCommand(call);
            }
            logger.info("Files with successful execution of flink sql script:{}", path);
        }

        logger.info("Flink task submitted successfully");

    }

    // --------------------------------------------------------------------------------------------

    private void callCommand(SqlCommandParser.SqlCommandCall cmdCall) {
        switch (cmdCall.command) {
            case SET:
                callSet(cmdCall);
                break;
            case CREATE_TABLE:
            case DROP_TABLE:
                callCreateTable(cmdCall);
                break;
            case INSERT_INTO:
            case SELECT_TABLE:
                callInsertInto(cmdCall);
                break;
            default:
                throw new RuntimeException("Unsupported command: " + cmdCall.command);
        }
    }

    private void callSet(SqlCommandParser.SqlCommandCall cmdCall) {
        String key = cmdCall.operands[0];
        String value = cmdCall.operands[1];
        tEnv.getConfig().getConfiguration().setString(key, value);
    }

    private void callCreateTable(SqlCommandParser.SqlCommandCall cmdCall) {
        String ddl = cmdCall.operands[0];
        try {
            tEnv.executeSql(ddl);
        } catch (SqlParserException e) {
            throw new RuntimeException("SQL parse failed:\n" + ddl + "\n", e);
        }
    }

    private void callInsertInto(SqlCommandParser.SqlCommandCall cmdCall) {
        String dml = cmdCall.operands[0];
        try {
            tEnv.executeSql(dml);
        } catch (SqlParserException e) {
            throw new RuntimeException("SQL parse failed:\n" + dml + "\n", e);
        }
    }
}
